<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Userprojecttaskreport as TaskreportMdl;
use app\admin\model\Userprojecttask;
use app\admin\model\Userproject;
use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

class Userprojecttaskreport extends BaseController
{

    /**
     * 列表
     */
    public function getReports()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->taskId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'taskId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $taskId = $param->taskId;
        $where = [
            'taskId' => $taskId
        ];

        $model = new TaskreportMdl();
        $fields = '*';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        foreach ($result as $item) {
            // 图片
            $item['imgList'] = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 保存
     */
    public function saveReport()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->taskId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '任务ID(taskId) 不能为空');
        }
        if (empty($param->reportTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '汇报时间(reportTime) 不能为空');
        }
        if (empty($param->content)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '汇报内容(content) 不能为空');
        }
        if (empty($param->isComplete)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '任务完成情况(isComplete) 不能为空');
        }

        Db::startTrans();
        try {
            $data = (array)$param;
            $model = new TaskreportMdl();

            if (!empty($param->id)) {
                $id = $param->id;
                $data['id'] = $id;
                $data['updateDate'] = time();

                $result = $model->allowField(true)->save($data, ['id' => $id]);
            } else {
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();

                $result = $model->save($data);
            }

            if($result !== false){
                // 图片
                $imgRes = '';
                if(isset($param->imgUrls) && $param->imgUrls) {
                    $imgUrls = (array) $param->imgUrls;
                    foreach($imgUrls as $key => $imgUrl){
                        $imgRes = Image::where(['imgUrl' => $imgUrl])->update(['relatedId' => $data['id'], 'relatedTable' => 'userprojecttaskreport', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if($imgRes === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '保存图片失败');
                }

                $taskInfo = Userprojecttask::get($param->taskId);
                if ($param->isComplete == 1) {
                    // 任务已完成
                    //if ($taskInfo->deadline >= time()) {
                    if (date('Y-m-d', $taskInfo->deadline) >= date('Y-m-d', time())) {
                        $taskInfo->status = 1; // 按时完成
                    } else {
                        $taskInfo->status = 2; // 延期完成
                    }
                    // 完成时间
                    $taskInfo->completeTime = time();
                } else {
                    // 任务进行中
                    $taskInfo->status = 3;
                }
                // 更新任务状态
                $resTask = $taskInfo->save();
                if($resTask === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '更新任务状态失败', Userprojecttask::getError());
                }

                // 更新项目状态
                $projectId = $taskInfo->projectId;
                $projectInfo = Userproject::get($projectId);
                // 如果任务进行中，则项目也在进行中
                $projectInfo->status = 2;
                // 如果任务已完成
                if ($param->isComplete == 1) {
                    // 总任务数
                    $totalTask = Userprojecttask::where(['projectId' => $projectId])->count();
                    // 已完成任务数
                    // TODO 虽然没有 Db::commit()，但是任务的修改在这里已经生效
                    $completeTask = Userprojecttask::where(['projectId' => $projectId, 'status' => ['in', '1,2']])->count();
                    if ($totalTask == $completeTask) {
                        // 项目已完成
                        $projectInfo->status = 1;
                    }
                }
                $resProject = $projectInfo->save();
                if($resProject === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '更新项目状态失败', Userproject::getError());
                }

                Db::commit();
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '保存失败', $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '保存失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 删除
     */
    public function delReport()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }
        if (empty($param->taskId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '任务ID(taskId) 不能为空');
        }

        $where = [
            'id' => $param->id
        ];

        Db::startTrans();
        try {
            $model = new TaskreportMdl();
            $result = $model->where($where)->delete();
            if ($result === false) {
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
            }

            // 汇报是否已全部删除
            $count = $model->where(['taskId' => $param->taskId])->count();
            if($count == 0){
                // 更新任务状态
                $taskInfo = Userprojecttask::get($param->taskId);
                $taskInfo->status = 0; // 状态改为未完成
                $resTask = $taskInfo->save();
                if($resTask === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '更新任务状态失败', Userprojecttask::getError());
                }

                // 更新项目状态
                $projectId = $taskInfo->projectId;
                $projectInfo = Userproject::get($projectId);
                // 是否有进行中的任务
                $processingTask = Userprojecttask::where(['projectId' => $projectId, 'status' => 3])->count();
                if ($processingTask > 0) {
                    // 项目进行中
                    $projectInfo->status = 2;
                } else {
                    // 项目未开始
                    $projectInfo->status = 0;
                }
                $resProject = $projectInfo->save();
                if($resProject === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), '更新项目状态失败', Userproject::getError());
                }
            }

            Db::commit();

            // Query执行后的操作
            $model->_after_delete($param->id);
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '保存失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /**
     * 更新项目状态
     */
    protected function updateProject(){
        //
    }
}